package com.example.orderserver.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.example.orderserver.exception.FeignMyException;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;

import java.io.IOException;
import java.nio.charset.Charset;

/**
 * @author benjamin_5
 * @Description Feign响应状态码非2xx时触发的异常处理解析器
 * @date 2023/3/10
 */
public class FeignErrorDecoder implements ErrorDecoder {

    @Override
    public Exception decode(String methodKey, Response response) {
        try {
            String message = Util.toString(response.body().asReader(Charset.defaultCharset()));
            try {
                JSONObject result = JSON.parseObject(message);
                // 可定义成自己的Exception
                return new FeignMyException(result.getInteger("code") ,"报错啦");
            } catch (JSONException e) {
                e.printStackTrace();
            }

        } catch (IOException ignored) {
        }
        return decode(methodKey, response);
    }
}
